<template>
  <el-input v-bind="$attrs" v-on="listeners" @input="inputLimit" />
</template>
<script>
export default {
  name: 'LimitInput',
  inheritAttrs: false,
  props: {
    numb: {
      // 是否纯数字
      type: Boolean,
      default() {
        return false;
      },
    },
    space: {
      // 是否支持空格
      type: Boolean,
      default() {
        return false;
      },
    },
    pattern: {
      // 正则
      type: RegExp,
      default() {
        return null;
      },
    },
  },
  data() {
    return {
      listeners: {},
    };
  },
  created() {
    const { input, ...others } = this.$listeners;
    this.listeners = others;
  },
  methods: {
    inputLimit(val) {
      const { numb, space } = this;
      const maxlength = +this.$attrs.maxlength;
      const value = this.limiter(val, {
        numb,
        space,
        maxlength,
      });
      this.$emit('input', value);
      this.$emit('update:value', value);
    },
    limiter(content, opts = {}) {
      if ([undefined, null, ''].includes(content)) {
        return content;
      }
      const { maxlength, numb = false, space } = opts;
      let result = String(content);
      let reg = new RegExp(/[\s]/, 'g');
      if (space) reg = null;
      if (numb) reg = new RegExp(/[^0-9]/, 'g');

      reg && (result = result.replace(reg, ''));
      if (maxlength && maxlength > 0) result = result.slice(0, maxlength);

      return result;
    },
  },
};
</script>
